define(['jquery'],function($){
    class Header {
        constructor(){
            this.loadHTML().then(()=>{
                this.search()
                this.loginCheck()
                this.calcCartTotal()

            })
           
        }
        loadHTML() {
            return new Promise(resolve =>{
                $('header').load('/html/modules/header.html',resolve)
            })
        }
        search(){
            $('#searchInput').on('focus',()=>{
                $('#searchResult').css('display','block')
                
                $('#searchInput').on('keyup',function(){
                    $.getJSON('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?cb=?',{wd :$(this).val()},function(resp){
                        const { s } = resp
                        $('#searchResult').html(s.reduce((html,item)=>{
                            html+= `<li>${item}</li>`
                            return html
                        },''))
                        $('#searchResult li').on('mousedown',function(){
                            $('#searchInput').val($(this).html())
                        })
                    })
                })
                
            })
            $('#searchInput').on('blur',()=>{
                $('#searchResult').css('display','none')
            })
        }
        
        loginCheck(){
            var getcookie = document.cookie
            if(getcookie){
                let username = getcookie.split('=')
                username = username[1]
                $("#loginInfo").html(`你好，${username}`)
                this.logout()
                
            }else{
                this.login()
            }

        }
        login(){
            $('#userBtn').on('click',()=>location.replace('/html/login.html'))
        }
        logout(){
            $('#userBtn').on('click',()=>{
                if(confirm('确定退出登录？')){
                    let d = new Date()
                    d.setDate(d.getDate()-1)
                    document.cookie=`username=fdsf;expires=${d.toUTCString()};path=/`
                    location.reload()
                }
            })
        }
        calcCartTotal(){
            // 计算计算机总数量
            let count = 0
            let cart = localStorage.getItem('cart')
            if(cart){
                cart = JSON.parse(cart)
                count = cart.reduce((total,shop)=>{
                    return total + shop.count
                },0)
            }
            $('#shopnum').html(count)
            $('#cart').html(count)
        }

    }    
    return new Header()
})

